package cn.itsource.basic.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.itsource.basic.config.exception.BusinessException;
import cn.itsource.org.pojo.vo.LoginInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class LoginInfoUtil {

    /**
     * 获取用户id的方法
     * @return
     */
    public static Long getUserId(){
        //获取userId
        Long userId = getLoginInfo().getUserId();

        //验证
        if (userId == null){
            throw new BusinessException("你错了");
        }
        //返回
        return userId;
    }
    /**
     * 获取用户id的方法
     * @return
     */
    public static Long getShopId(){
        //获取shopId
        Long shopId = getLoginInfo().getShopId();

        //验证
        if (shopId == null){
            throw new BusinessException("你错了");
        }
        //返回
        return shopId;
    }

    /**
     * 获取登录对象
     * @return
     */
    public static LoginInfo getLoginInfo(){

        //1.获取请求对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //2.从请求对象中获取头信息，token字段
        String token = request.getHeader("token");

        //3.从redis获取token对应的值

        RedisService redisService = SpringUtil.getBean(RedisService.class);
        LoginInfo loginInfo = redisService.getKeyObjectValue(token, LoginInfo.class);

        //4.json字符串转成对象
        return loginInfo;

    }

}
